//
//  CollectionViewController.m
//  BeautyClother
//
//  Created by dllo on 15/9/2.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "CollectionViewController.h"

#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "define.h"
#import "StoreLayout.h"
#import "SuitCell.h"
#import "ItemsModel.h"
#import "ItemDataBase.h"
#import "DataBase.h"
#import "CollectionController.h"

@interface CollectionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) ItemsModel *model;

@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, retain) StoreLayout *flow;

@end

@implementation CollectionViewController


- (void)dealloc
{
    [_flow release];
    [_model release];
    [_collection release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.model = [[ItemsModel alloc]init];
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
        self.flow = [[StoreLayout alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self handleData];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(fanhui:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    self.title = @"我的收藏";
    
// Do any additional setup after loading the view.
}

- (void)fanhui:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (void)handleData
{
    [DataBase dataBaseOpen];
    self.array = (NSMutableArray *)[ItemDataBase selectAll];
    if (self.array.count == 0) {
        
        [self crectaMessage];
        
    }else
    {
    self.flow.dicArray = self.array;
    [self createOtherCollection:self.flow];
    }
    

}

- (void)crectaMessage
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 360 * _offHeight, 200 * _offWidth, 40 *_offHeight)];
    label.center = self.view.center;
    [self.view addSubview:label];
    label.text = @"等你收藏填饱我肚子哦";

}

- (void)createOtherCollection:(StoreLayout *)layout
{
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0 , 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:layout];
    
    self.collection.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:.1 alpha:0.1];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.collection registerClass:[SuitCell class] forCellWithReuseIdentifier:@"aaaa"];
    [self.view addSubview:self.collection];
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.array.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SuitCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"aaaa" forIndexPath:indexPath];
    
    self.model = [self.array objectAtIndex:indexPath.item];
    NSString *pic = [[self.model.picUrl componentsSeparatedByString:@"?"]objectAtIndex:0];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    
    [DataBase dataBaseOpen];
    
    [cell.like setTitle:self.model.collectionCount forState:UIControlStateNormal];
    
    
    [cell.like setImage:[UIImage imageNamed:@"sheart.png"] forState:UIControlStateNormal];
    
    cell.like.tag = indexPath.item;
    cell.like.selected = YES;
    [cell.like addTarget:self action:@selector(cancle:) forControlEvents:UIControlEventTouchUpInside];
    

    NSInteger i = [self.model.collectionCount integerValue];
    [cell.share setTitle:[NSString stringWithFormat:@"%ld", i + 1] forState:UIControlStateNormal];
    cell.title.text = self.model.desc;

    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    cell.backgroundColor = [UIColor whiteColor];
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.model = [self.array objectAtIndex:indexPath.item];
    CollectionController *coll = [[CollectionController alloc]init];
    coll.aid = self.model.iid;
    coll.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:coll animated:YES];
    [coll release];
}



- (void)cancle:(UIButton *)button
{
    
    
    
    if (button.selected == YES) {
        ItemsModel *model = [self.array objectAtIndex:button.tag];
        [DataBase dataBaseOpen];
        [ItemDataBase deleteWithid:model.iid];
        NSInteger i = [model.collectionCount integerValue];
        i = i - 1;
        [button setTintColor:[UIColor darkGrayColor]];
        [button setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        [DataBase dataBaseOpen];
        NSMutableArray *array = (NSMutableArray *)[ItemDataBase selectAll];

        self.array = array;
        CGFloat hei = self.collection.contentOffset.y;

        [self.collection removeFromSuperview];
        StoreLayout *lay = [[StoreLayout alloc]init];
        lay.dicArray= array;
        [self createOtherCollection:lay];
        
        [self.collection reloadData];
        self.collection.contentOffset = CGPointMake(0, hei);
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 150 * _offWidth, 60 *_offHeight)];
        
        image.center = self.view.center;
        [self.view addSubview:image];
        image.layer.cornerRadius = 5;
        image.layer.masksToBounds = YES;
        image.backgroundColor = [UIColor lightGrayColor];
        [image release];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150 * _offWidth, 60 *_offHeight)];
        label.text = @"取消收藏成功";
        
        label.textAlignment = 1;
        [image addSubview:label];
        label.textColor = [UIColor whiteColor];
        [label release];
        [UIView animateWithDuration:1.5 animations:^{
            
            image.alpha = 0.2;
            
        } completion:^(BOOL finished) {
            [image removeFromSuperview];
        }];
        
        if (array.count == 0) {
            [self crectaMessage];
        }
        
    }

    if (button.selected == NO) {
        ItemsModel *model = [self.array objectAtIndex:button.tag];
        NSInteger i = [model.collectionCount integerValue];
        [ItemDataBase insertWithModel:model];
        
        [button setImage:[UIImage imageNamed:@"sheart.png"] forState:UIControlStateNormal];
        [button setTintColor:[UIColor clearColor]];
        i = i;
        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        
    }
    if (button.selected == YES) {
        button.selected = NO;
    }else
    {
        button.selected = YES;
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
